<?php

//Add metabox to Page template

add_action('admin_menu', 'addMetaBox');
add_action('save_post', 'saveMetaData', 10, 2);
add_action('admin_head', 'embedUploaderCode');
 
//Define the metabox attributes.
$metaBox = array(
  'id'     => 'arc_backimg_metabox',
  'title'    => 'Custom Background Image',
  'page'     => 'page',
  'context'  => 'normal',
  'priority'   => 'high',
  'fields' => array(
    array(
      'name'   => 'Custom Image',
      'desc'   => 'If you choose the "Background with image" template or the "News Template", use this form to upload the photo you want.<br><em>Recommended photo size: 882 x 564 px</em>',
      'id'  => 'arc_custom_background_image',  //value is stored with this as key.
      'class' => 'image_upload_field',
      'type'   => 'media'
    )
  )
);

//Metabox 2
//Define the metabox attributes.
$metaBox2 = array(
  'id'     => 'arc_sliderimg_metabox',
  'title'    => 'Custom Slider Images',
  'page'     => 'page',
  'context'  => 'normal',
  'priority'   => 'high',
  'fields' => array(
    array(
      'name'   => 'Custom Images',
      'desc'   => 'If you choose the "Background with slider" template, use this area to insert the photo\'s url you want in the slider, <u>one per line</u>.<br><em>Recommended photo size: 882 x 564 px</em>',
      'id'  => 'arc_custom_slider_images',  //value is stored with this as key.
      'class' => 'image_upload_field',
      'type'   => 'textarea'
    )
  )
);
 
function addMetaBox() {
  global $metaBox, $metaBox2;
  add_meta_box($metaBox['id'], $metaBox['title'], 'createMetaBox', 
    $metaBox['page'], $metaBox['context'], $metaBox['priority']);
  add_meta_box($metaBox2['id'], $metaBox2['title'], 'createMetaBox2', $metaBox2['page'], $metaBox2['context'], $metaBox2['priority']);
 
}

/**
* Create Metabox HTML.
*/
function createMetaBox($post) {
  global $metaBox;
  if (function_exists('wp_nonce_field')) {
    wp_nonce_field('awd_nonce_action','awd_nonce_field');
  }
 
  foreach ($metaBox['fields'] as $field) {
    echo '<div class="awdMetaBox2">';
    //get attachment id if it exists.
    $meta = get_post_meta($post->ID, $field['id'], true);
    switch ($field['type']) {
      case 'media':
?>
        <p><?php echo $field['desc']; ?></p>
        <div class="awdMetaImage">
<?php 
        if ($meta) {
          echo wp_get_attachment_image( $meta, 'thumbnail', true);
          $attachUrl = wp_get_attachment_url($meta);
          echo '<p>URL: <a target="_blank" href="'.$attachUrl.'">'.$attachUrl.'</a></p>';
        }
?>    
        </div><!-- end .awdMetaImage -->
        <p>
          <input type="hidden" 
            class="metaValueField" 
            id="<?php echo $field['id']; ?>" 
            name="<?php echo $field['id']; ?>"
            value="<?php echo $meta; ?>" 
          /> 
          <input class="image_upload_button"  type="button" value="Choose File" /> 
          <input class="removeImageBtn" type="button" value="Remove File" />
        </p>
 
<?php
      break;
    }
    echo '</div> <!-- end .awdMetaBox -->';
  } //end foreach
}//end function createMetaBox
 
/**
* Create Metabox2 HTML.
*/
function createMetaBox2($post) {
  global $metaBox2;
  if (function_exists('wp_nonce_field')) {
    wp_nonce_field('awd_nonce_action','awd_nonce_field');
  }
 
  foreach ($metaBox2['fields'] as $field) {
    echo '<div class="awdMetaBox2">';
    //get attachment id if it exists.
    $meta = get_post_meta($post->ID, $field['id'], true);
?>
        <p><?php echo $field['desc']; ?></p>

        <p>
		  <textarea id="<?php echo $field['id']; ?>" 
          name="<?php echo $field['id']; ?>"
		  style="width: 650px; height: 190px"><?php echo $meta; ?></textarea>
        </p>
 
<?php
    echo '</div> <!-- end .awdMetaBox2 -->';
  } //end foreach
}//end function createMetaBox2
 
 
function saveMetaData($post_id, $post) {
  //make sure we're saving at the right time.
  //DOING_AJAX is set when saving a quick edit on the page that displays all posts/pages  
  //Not checking for this will cause our meta data to be overwritten with blank data.
  if ( empty($_POST)
    || !wp_verify_nonce($_POST['awd_nonce_field'],'awd_nonce_action')
    || $post->post_type == 'revision'
    || defined('DOING_AJAX' )) {
    return;
  }
 
  global $metaBox, $metaBox2;
  global $wpdb;
 
  foreach ($metaBox['fields'] as $field) {
    $value = $_POST[$field['id']];
 
    if ($field['type'] == 'media' && !is_numeric($value) ) {
      //Convert URL to Attachment ID.
      $value = $wpdb->get_var(
        "SELECT ID FROM $wpdb->posts 
         WHERE guid = '$value' 
         AND post_type='attachment' LIMIT 1");
    }
    update_post_meta($post_id, $field['id'], $value);
  }//end foreach
  
  //For metabox2
  foreach ($metaBox2['fields'] as $field) {
    $value = $_POST[$field['id']];
    update_post_meta($post_id, $field['id'], $value);
  }//end foreach
}//end function saveMetaData
 
/**
 * Add JavaScript to get URL from media uploader.
 */
function embedUploaderCode() {
  ?>
  <script type="text/javascript">
  jQuery(document).ready(function() {
 
    jQuery('.removeImageBtn').click(function() {
      jQuery(this).closest('p').prev('.awdMetaImage').html('');   
      jQuery(this).prev().prev().val('');
      return false;
    });
 
    jQuery('.image_upload_button').click(function() {
      inputField = jQuery(this).prev('.metaValueField');
      tb_show('', 'media-upload.php?TB_iframe=true');
      window.send_to_editor = function(html) {
        url = jQuery(html).attr('href');
        inputField.val(url);
        inputField.closest('p').prev('.awdMetaImage').html('<p>URL: '+ url + '</p><p>Image:<br> <img src="'+ url + '" width="150px" /></p>');  
        tb_remove();
      };
      return false;
    });
  });
 
  </script>
  <?php
}//end function embedUploaderCode()